There arenbulbs that are initially off. You first turn on all the bulbs. Then, you turn off every second bulb. On the third round, you toggle every third bulb (turning on if it's off or turning off if it's on). For theith round, you toggle everyibulb. For thenth round, you only toggle the last bulb. Find how many bulbs are on afternrounds.

Example:

Given 
n
 = 3. 



At first, the three bulbs are 
[off, off, off]
.
After first round, the three bulbs are 
[on, on, on]
.
After second round, the three bulbs are 
[on, off, on]
.
After third round, the three bulbs are 
[on, off, off]
. 



So you should return 1, because there is only one bulb is on.

class Solution {

public:

int bulbSwitch\(int n\) {

    //int count=0;

    //int blub\[n+1\]={0};





   /\* for\(int k=1;k<=n;k++\){

        for\(int i=k;i<=n;i=i+k\){

                blub\[i\]++;

        }

    }



    for \(int i=1;i<=n;i++\){

        count+=\(blub\[i\]%2==0\)?0:1;

    }



    return count;\*/

    return sqrt\(n\);

}

};

这个是真的很巧妙。

因为只有在divisor个数为偶数的时候,才会关掉。同时,divisor都是成对出现的,所以只有一种情况下,也就是是平凡数的时候,他是会有单个的情况。所以。。。

results matching ""

    No results matching ""